package main

import (
	"iot-base/common/cache"
	"iot-base/common/notify"
	"net"
	"strconv"
	"strings"
	"time"

	"fmt"

	"errors"
)

func GetClinkTask(id string, thing *cache.ThingInfo, v interface{}, round int64) (interface{}, error) {
	fmt.Println("in clink", thing)
	ip := thing.GetThingParam("ip", "")
	if ip == "" {
		fmt.Println("ip is nil")
		return nil, errors.New("ip is nil")
	}
	port := thing.GetThingParam("port", "")
	if port == "" {
		fmt.Println("port is nil")
		return nil, errors.New("port is nil")
	}
	conn, err := net.DialTimeout("tcp", ip+":"+port, 3*time.Second)
	if err != nil {
		fmt.Println("connect " + ip + " err:" + err.Error())
		return nil, errors.New("connect " + ip + " err:" + err.Error())
	}
	now := time.Now().Unix()
	switch thing.Thing.ModelID {
	case "m_nox":
		res, err := order("no", conn)
		if err != nil {
			return nil, err
		}
		result := strings.Split(res, " ")
		notify.RawData(id, "no", "", 0, MulCount(result[1]), now, now)
		res, err = order("no2", conn)
		if err != nil {
			return nil, err
		}
		result = strings.Split(res, " ")
		notify.RawData(id, "no2", "", 0, MulCount(result[1]), now, now)
		res, err = order("nox", conn)
		if err != nil {
			return nil, err
		}
		result = strings.Split(res, " ")
		notify.RawData(id, "nox", "", 0, MulCount(result[1]), now, now)
		res, err = order("nox", conn)
		if err != nil {
			return nil, err
		}
		result = strings.Split(res, " ")
		notify.RawData(id, "nox", "", 0, MulCount(result[1]), now, now)
	case "m_co":
		res, err := order("co", conn)
		if err != nil {
			return nil, err
		}
		result := strings.Split(res, " ")
		notify.RawData(id, "co", "", 0, MulCount(result[1]), now, now)
	case "m_o3":
		res, err := order("o3", conn)
		if err != nil {
			return nil, err
		}
		result := strings.Split(res, " ")
		notify.RawData(id, "o3", "", 0, MulCount(result[1]), now, now)
	case "m_so2":
		res, err := order("so2", conn)
		if err != nil {
			return nil, err
		}
		result := strings.Split(res, " ")
		notify.RawData(id, "so2", "", 0, MulCount(result[1]), now, now)
	default:
		return nil, errors.New("no this thing")
	}
	return nil, nil
}

func order(order string, conn net.Conn) (string, error) {
	_, err := conn.Write([]byte(order + string(0x0D)))
	if err != nil {
		fmt.Println("conn write err:" + err.Error())
		return "", errors.New("conn write err!")
	}
	res := make([]byte, 1024)
	n, err := conn.Read(res)
	if err != nil || n == 0 {
		fmt.Println("conn read err" + err.Error())
		return "", errors.New("conn read err" + err.Error())
	}
	return string(res[:n]), nil
}

func MulCount(input string) string {
	len := len(input)
	count, _ := strconv.ParseFloat(string(input[:len-4]), 10)
	mul, _ := strconv.ParseFloat(string(input[len-2:len]), 10)
	var result float64
	if mul != 0 {
		result = count * mul * 10
	} else {
		result = count
	}
	fmt.Println(fmt.Sprintf("%.2f", result))
	return fmt.Sprintf("%.2f", result)
}
